﻿using PLCS.Application.Contracts.HisTaskApp;
using PLCS.Application.Contracts.HisTaskApp.Dtos;
using PLCS.Application.Contracts.Params;
using PLCS.Application.Contracts.TaskApp.Dtos;
using PLCS.Domain.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;

namespace PLCS.Application.HisTaskApp;

public class HisTaskAppService : CrudAppService<HisTask, HisTaskDto, Guid, PagedResultRequestDto, HisTaskEditDto>, IHisTaskAppService
{
    private readonly IHisTaskRepository _hisTaskRepository;
    private readonly ITaskRepository _taskRepository;

    public HisTaskAppService(IHisTaskRepository hisTaskRepository, ITaskRepository taskRepository) : base(hisTaskRepository)
    {
        _hisTaskRepository = hisTaskRepository;
        _taskRepository = taskRepository;
    }

    public async Task AgainIssuedAsync(HisTaskDto hisTask)
    {
        var entity = ObjectMapper.Map<HisTaskDto, HisTask>(hisTask);
        TaskModel task = ObjectMapper.Map<HisTask, TaskModel>(entity);
        task.ChangeStatus(Domain.Shared.Tasks.TaskStatus.未执行);
        await _taskRepository.InsertAsync(task);
        await _hisTaskRepository.DeleteAsync(entity);
    }

    public async Task<PagedResultDto<HisTaskDto>> GetListBySearchAsync(PagedResultRequestDto input, string? taskNo, string? startTime, string? endTime)
    {
        await CheckGetListPolicyAsync();

        var query = await CreateFilteredQueryAsync(input);
        query = query.OrderByDescending(x => x.CreationTime);
        bool isTaskId = int.TryParse(taskNo, out int intTaskId);
        query = query.WhereIf(isTaskId, x => x.TaskId == intTaskId);
        bool isStartTime = DateTime.TryParse(startTime, out DateTime StartDateTime);
        query = query.WhereIf(isStartTime, x => x.CreationTime > StartDateTime);
        bool isEndTime = DateTime.TryParse(endTime, out DateTime EndDateTime);
        query = query.WhereIf(isEndTime, x => x.CreationTime < EndDateTime);
        var totalCount = await AsyncExecuter.CountAsync(query);

        query = ApplyPaging(query, input);

        var entities = await AsyncExecuter.ToListAsync(query);
        var entityDtos = await MapToGetListOutputDtosAsync(entities);

        return new PagedResultDto<HisTaskDto>(
            totalCount,
            entityDtos
        );
    }
}